using Com.FirstSolver.Splash;
using Mina.Filter.Codec;
using Mina.Transport.Socket;
using System.Net;

namespace HanwangService
{
    public class WorkerUDP : BackgroundService
    {


        /// <summary>
        /// 服务器是否已运行
        /// </summary>
        private bool IsServerRunning = false;

        /// <summary>
        /// 侦听服务器
        /// </summary>
        private AsyncDatagramAcceptor UdpServer = null;
        private string IP = "0.0.0.0";
        private readonly ILogger<Worker> _logger;
        private readonly int port = 9904;
        private readonly bool hasTask = true;

        public WorkerUDP(ILogger<Worker> logger)
        {
            _logger = logger;
            Starservice();
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                if (_logger.IsEnabled(LogLevel.Information))
                {
                    //_logger.LogInformation("UDP Worker running at: {time}", DateTimeOffset.Now);
                }
                await Task.Delay(30000, stoppingToken);
            }
        }

        private void Starservice()
        {


            if (IsServerRunning)
            {   // 停止侦听
                if (UdpServer != null)
                {
                    UdpServer.Dispose();
                    UdpServer = null;
                }

                IsServerRunning = false;
                _logger.LogInformation($"UDP停止侦听 : {port}");
            }
            else
            {
                // 开启侦听
                UdpServer = new AsyncDatagramAcceptor();
                UdpServer.FilterChain.AddLast("codec", new ProtocolCodecFilter(new FaceReaderProtocolCodecFactory(false, null)));
                UdpServer.SessionConfig.ReuseAddress = true;
                // 设置事件处理器
                UdpServer.MessageReceived += (s, ea) =>
                {   // 显示接收字符串
                    string Message = (string)ea.Message;

                    _logger.LogInformation(Message);



                    // 判断是否有命令下发
                    if (hasTask)
                    {   // 通知设备有命令要发送
                        /*{
                            "RETURN":"DevStatus",
                            "PARAM":{
                                                            "result":"success/fail",
                                "reason":"",
                                "command":"PostRequest"

                            }
                        }*/
                        //ea.Session.Write("PostRequest()");

                        REPLY_HEARTBEAT_TYPE rht = new REPLY_HEARTBEAT_TYPE();
                        rht.PARAM = new PARAM_REPLY_HEARTBEAT_TYPE();
                        ea.Session.Write(JsonHelper.ToJsonString(rht));
                        _logger.LogInformation("Send: " + JsonHelper.ToJsonString(rht) + "\r\n");

                    }

                };

                UdpServer.ExceptionCaught += (s, ea) =>
                {   // 线程安全性
                    _logger.LogError(ea.Exception.Message);

                    ea.Session.Close(true);
                };

                // 绑定侦听端口，开始侦听
                UdpServer.Bind(new IPEndPoint(IPAddress.Parse(IP), port));

                IsServerRunning = true;
                _logger.LogInformation($"UDP开始侦听 : {port}");
            }
        }
    }
}
